package com.longdaji.decoration.ui.activitiesOfMine.pendingEvaluated;

import android.content.Context;
import android.net.Uri;
import android.util.Log;

import com.google.gson.Gson;
import com.longdaji.decoration.Constants;
import com.longdaji.decoration.DecorationApplication;
import com.longdaji.decoration.base.RxPresenter;
import com.longdaji.decoration.bean.Account;
import com.longdaji.decoration.bean.AddComment;
import com.longdaji.decoration.bean.GoodsComment;
import com.longdaji.decoration.bean.Order;
import com.longdaji.decoration.bean.Orders;
import com.longdaji.decoration.bean.QiNiuInfo;
import com.longdaji.decoration.data.DataManager;
import com.longdaji.decoration.data.bean.GoodsCommentBean;
import com.longdaji.decoration.data.bean.GoodsImagesBean;
import com.longdaji.decoration.data.network.CommonSubscriber;
import com.longdaji.decoration.data.network.HttpResponse;
import com.longdaji.decoration.utils.LogUtil;
import com.longdaji.decoration.utils.PortraitAddressUtil;
import com.longdaji.decoration.utils.RxUtil;
import com.longdaji.decoration.utils.TimeUtil;
import com.qiniu.android.common.AutoZone;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Kanade on 2018/4/9 0009.
 */

public class EvaluatePresenter extends RxPresenter<EvaluateContract.IView> implements EvaluateContract.IPresenter {
    private static final String TAG = "EvaluatePresenter";
    private DataManager mDataManager;
    List<Orders.OrdersBean.OrderBean.ProductsBean> mProductsList = new ArrayList<>();

    private Configuration config;
    private UploadManager uploadManager;
    private String qiNiuToken;
    private boolean isUpLoadSuccess = true;

    @Inject
    public EvaluatePresenter(DataManager dataManager) {
        this.mDataManager = dataManager;
        initQiNiu();
    }

    private void initQiNiu() {
        config = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .zone(AutoZone.autoZone)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
// 重用uploadManager。一般地，只需要创建一个uploadManager对象
        uploadManager = new UploadManager(config);

        //获取token
        addSubscribe(mDataManager.doGetUpTokenApi()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new CommonSubscriber<HttpResponse>() {
                    @Override
                    public void onSuccess(HttpResponse httpResponse) {
                        LogUtil.d("succeed : doGetUpTokenApi " + httpResponse.getData().toString());
//                        mView.showQiNiuToken(httpResponse.getData().toString());
                        qiNiuToken = httpResponse.getData().toString();
                    }

                    @Override
                    public void onFailed(String msg) {
                        LogUtil.d("failed doGetUpTokenApi: " + msg);
                    }
                }));
    }

    @Override
    public void onAnonymousClick(boolean isAnonymous) {
        if (isAnonymous) {
            mView.showAnonymous(false);
        } else {
            mView.showAnonymous(true);
        }
    }


    @Override
    public void onCommentClick(int degree) {
        switch (degree) {
            case Constants.HIGH:
                mView.showCommentChosen(Constants.HIGH);
                break;
            case Constants.MEDIUM:
                mView.showCommentChosen(Constants.MEDIUM);
                break;
            case Constants.NEGATIVE:
                mView.showCommentChosen(Constants.NEGATIVE);
                break;
            default:
                break;
        }
    }

    @Override
    public void initGoods(int goodsId) {
        addSubscribe(mDataManager.getGoodsImages(String.valueOf(goodsId))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxUtil.<GoodsImagesBean>handleResult())
                .subscribeWith(new CommonSubscriber<GoodsImagesBean>() {
                    @Override
                    public void onSuccess(GoodsImagesBean goodsImagesBean) {
                        mView.showGoodsImage(goodsImagesBean.getGoodsImgs().get(0).getImgAddress());
                    }

                    @Override
                    public void onFailed(String msg) {
                        Log.d(TAG, "msg is " + msg);
                        if (mView != null) {
                            mView.toast(msg);
                        }
                    }
                }));
    }

    @Override
    public void onFinishClick(boolean isPhotoAdded, final String commentContent, final int goodsId, final String orderNo, final List<Uri> imgs) {
//        final List<String> imgsAfterUpload = new ArrayList<>();
//        imgsAfterUpload = doUploadPhoto(imgs);
        final int commentLike = 0;
        final int commentScore = 0;
        final String goodsName = null;
        final String userId = Account.getInstance().getUserid();
        final String userName = Account.getInstance().getUsername();

        if (isPhotoAdded) {
            final List<String> imgsList = new ArrayList<>();
            final int length = imgs.size();
            for (Uri uri : imgs) {
                String realUri = PortraitAddressUtil.getRealPathFromUri(DecorationApplication.getInstance().getApplicationContext(), uri);
                LogUtil.d("uploadtest", uri + "------" + realUri + "------" + qiNiuToken);
                uploadManager.put(realUri, TimeUtil.getEasyNowDate(), qiNiuToken,
                        new UpCompletionHandler() {
                            @Override
                            public void complete(String key, ResponseInfo info, JSONObject res) {
                                //res包含hash、key等信息，具体字段取决于上传策略的设置
                                if (info.isOK()) {
                                    Gson gson = new Gson();
                                    QiNiuInfo bean = gson.fromJson(res.toString(), QiNiuInfo.class);
                                    imgsList.add(Constants.QINIU_URL + bean.getKey());
                                    //imgs上传完毕
                                    if (imgsList.size() == length) {
//                                    doLoadSuccess(commentContent,goodsId,orderNo);
                                        LogUtil.d("imgtest", "imgs: " + imgsList.size());
                                        //这里应该是不需要传的


                                        List<GoodsComment.CommentImgsBean> commentImgsList = new ArrayList<>();
                                        for (String uri : imgsList) {
                                            GoodsComment.CommentImgsBean commentImgsBean = new GoodsComment.CommentImgsBean();
                                            commentImgsBean.setImgAddress(uri);
                                            commentImgsList.add(commentImgsBean);
                                        }

                                        GoodsComment goodsComment = new GoodsComment(commentContent, commentLike, commentScore, goodsId, goodsName, userId, userName, commentImgsList, orderNo);
                                        doGoodsComment(goodsComment);
                                    }
                                } else {
                                    LogUtil.i("qiniu", "Upload Fail");
                                    isUpLoadSuccess = false;
                                    //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                                }
                                LogUtil.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                            }
                        }, null);
            }
        } else {
            GoodsComment goodsComment = new GoodsComment(commentContent, commentLike, commentScore, goodsId, goodsName, userId, userName, null, orderNo);
            doGoodsComment(goodsComment);
        }


    }

    private List<String> doUploadPhoto(List<Uri> uriList) {
        final List<String> imgsList = new ArrayList<>();
        final int length = uriList.size();
        for (Uri uri : uriList) {
            String realUri = PortraitAddressUtil.getRealPathFromUri(DecorationApplication.getInstance().getApplicationContext(), uri);
            LogUtil.d("uploadtest", uri + "------" + realUri + "------" + qiNiuToken);
            uploadManager.put(realUri, TimeUtil.getEasyNowDate(), qiNiuToken,
                    new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject res) {
                            //res包含hash、key等信息，具体字段取决于上传策略的设置
                            if (info.isOK()) {
                                Gson gson = new Gson();
                                QiNiuInfo bean = gson.fromJson(res.toString(), QiNiuInfo.class);
                                imgsList.add(Constants.QINIU_URL + bean.getKey());
                            } else {
                                LogUtil.i("qiniu", "Upload Fail");
                                isUpLoadSuccess = false;
                                //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                            }
                            LogUtil.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                        }
                    }, null);
        }
        if (!isUpLoadSuccess)
            return null;
        return imgsList;

    }

    private void doGoodsComment(GoodsComment goodsComment) {
        addSubscribe(mDataManager.doGoodsCommentApi(goodsComment)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new CommonSubscriber<HttpResponse>() {
                    @Override
                    public void onSuccess(HttpResponse httpResponse) {
                        LogUtil.d(TAG, "success, doGoodsComment: " + httpResponse.getMessage());
                        mView.showDoGoodsCommentSuccess();
                    }

                    @Override
                    public void onFailed(String msg) {
                        LogUtil.d(TAG, "fail, doGoodsComment: " + msg);
                    }
                }));
    }
//
//    @Override
//    public void initList(final String orderNo) {
//        // TODO: 2018/4/30 0030 根据订单查询到所有的商品
//        addSubscribe(mDataManager.doGetOrderApi(Account.getInstance().getUserid(), null, orderNo)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .compose(RxUtil.<Orders>handleResult())
//                .subscribeWith(new CommonSubscriber<Orders>() {
//                    @Override
//                    public void onSuccess(Orders orders) {
//                        LogUtil.d(TAG, "success : doGetOrderApi: " + orderNo + ": --- " + orders.getOrders().getOrder().size());
//                        // TODO: 2018/5/8 0008 这里只是暂时去掉，因为现在的数据有重复的订单号
//                        /*if (orders.getOrders().getOrder().size() != 1) {
//                            LogUtil.d(TAG, "get order error");
//                            return;
//                        }*/
//
//                        Orders.OrdersBean.OrderBean order = orders.getOrders().getOrder().get(0);
//                        mProductsList = order.getProducts();
//                        List<AddComment> addCommentList = new ArrayList<>();
//                        for (Orders.OrdersBean.OrderBean.ProductsBean product : mProductsList) {
//                            AddComment addComment = new AddComment(product.getGoodsSkuImg(), Constants.HIGH, null, new ArrayList<Uri>(), false, product.getGoodsId(), product.getGoodsName());
//                            addCommentList.add(addComment);
//                        }
//
//                        mView.showInitList(addCommentList);
////                        //这里只是测试用,等XH改好用上面的订单编号获取订单方式
////                        for (Orders.OrdersBean.OrderBean orderBean : orders.getOrders().getOrder()) {
////                            if (Constants.ORDER_FINISHED == orderBean.getOrderStatus()) {
////                                LogUtil.d(TAG,"11111111");
////                                mView.showInitList(orderBean.getProducts());
////                                break;
////                            }
////                        }
//
//                    }
//
//                    @Override
//                    public void onFailed(String msg) {
//
//                    }
//                }));
//    }



    /*
    * 一次评价多个商品(淘宝)
    * */
//    private static final String TAG = "EvaluatePresenter";
//    private DataManager mDataManager;
//    List<Orders.OrdersBean.OrderBean.ProductsBean> mProductsList = new ArrayList<>();
//    private int doCommentCalculate = 0;
//
//    private Configuration config;
//    private UploadManager uploadManager;
//    private String qiNiuToken;
//    private boolean isUpLoadSuccess = true;
//
//    @Inject
//    public EvaluatePresenter(DataManager dataManager) {
//        this.mDataManager = dataManager;
//        initQiNiu();
//    }
//
//    private void initQiNiu() {
//        config = new Configuration.Builder()
//                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
//                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
//                .connectTimeout(10)           // 链接超时。默认10秒
//                .useHttps(true)               // 是否使用https上传域名
//                .responseTimeout(60)          // 服务器响应超时。默认60秒
//                .zone(FixedZone.zone0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
//                .build();
//// 重用uploadManager。一般地，只需要创建一个uploadManager对象
//        uploadManager = new UploadManager(config);
//
//        //获取token
//        addSubscribe(mDataManager.doGetUpTokenApi()
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribeWith(new CommonSubscriber<HttpResponse>() {
//                    @Override
//                    public void onSuccess(HttpResponse httpResponse) {
//                        LogUtil.d("succeed : doGetUpTokenApi " + httpResponse.getData().toString());
////                        mView.showQiNiuToken(httpResponse.getData().toString());
//                        qiNiuToken = httpResponse.getData().toString();
//                    }
//
//                    @Override
//                    public void onFailed(String msg) {
//                        LogUtil.d("failed doGetUpTokenApi: " + msg);
//                    }
//                }));
//    }
//
////    @Override
////    public void onAnonymousClick(boolean isAnonymous) {
////        if (isAnonymous) {
////            mView.showAnonymous(false);
////        } else {
////            mView.showAnonymous(true);
////        }
////    }
//
////    @Override
////    public void onCommentClick(int degree) {
////        switch (degree) {
////            case Constants.HIGH:
////                mView.showCommentChosen(Constants.HIGH);
////                break;
////            case Constants.MEDIUM:
////                mView.showCommentChosen(Constants.MEDIUM);
////                break;
////            case Constants.NEGATIVE:
////                mView.showCommentChosen(Constants.NEGATIVE);
////                break;
////            default:
////                break;
////        }
////    }
//
////    @Override
////    public void onFinishClick(String orderNo) {
////        //1.根据订单号获取当前订单，进而获取订单中所有的商品id，并对每一个商品进行评价?这里问下交互
////        addSubscribe(mDataManager.doGetOrderApi(Account.getInstance().getUserid(), null, orderNo)
////                .subscribeOn(Schedulers.io())
////                .observeOn(AndroidSchedulers.mainThread())
////                .compose(RxUtil.<Orders>handleResult())
////                .subscribeWith(new CommonSubscriber<Orders>() {
////                    @Override
////                    public void onSuccess(Orders orders) {
////                        LogUtil.d(TAG, "success : doGetOrderApi");
////                        if (orders.getOrders().getOrder().size() != 1) {
////                            LogUtil.d(TAG, "get order error");
////                            return;
////                        }
////                        int productCount = orders.getOrders().getOrder().get(0).getProductCount();
////                        List<Orders.OrdersBean.OrderBean.ProductsBean> products = orders.getOrders().getOrder().get(0).getProducts();
////                        for (Orders.OrdersBean.OrderBean.ProductsBean product : products) {
////                            // TODO: 2018/4/30 0030 这里应该是先加入ID和评论信息构成一个GoodsComment，然后doGoodsComment
////                            GoodsComment goodsComment = new GoodsComment();
////                            doGoodsComment(goodsComment);
////                        }
////
////
////                    }
////
////                    @Override
////                    public void onFailed(String msg) {
////
////                    }
////                }));
////
////
////    }
//
//    @Override
//    public void onFinishClick(String orderNo, List<AddComment> addCommentList) {
//        for (AddComment addComment : addCommentList) {
//            String commentContent = addComment.getCommentContent();
//            List<String> imgsListAfterUpLoad = new ArrayList<>();
//            int commentLike = 0;
//            int commentScore = 0;
//            int goodsId = addComment.getGoodsId();
//            String goodsName = addComment.getGoodsName();
//            String userName = Account.getInstance().getName();
//            String userId = Account.getInstance().getUserid();
//
//            imgsListAfterUpLoad = doUpLoadPhoto(addComment.getCommentImages());
//            if (imgsListAfterUpLoad == null) {
//                mView.showUploadFailed();
//                return;
//            }
//            List<GoodsComment.CommentImgsBean> commentImgsList = new ArrayList<>();
//            for (String uri : imgsListAfterUpLoad) {
//                GoodsComment.CommentImgsBean commentImgsBean = new GoodsComment.CommentImgsBean();
//                commentImgsBean.setImgAddress(uri);
//                commentImgsList.add(commentImgsBean);
//            }
//
//            GoodsComment goodsComment = new GoodsComment(commentContent, commentLike, commentScore, goodsId, goodsName, userId, userName, commentImgsList, orderNo);
//            doGoodsComment(goodsComment);
//        }
//    }
//
//    private List<String> doUpLoadPhoto(List<Uri> uriList) {
//        final List<String> imgsList = new ArrayList<>();
//        for (Uri uri : uriList) {
//            String realUri = PortraitAddressUtil.getRealPathFromUri(DecorationApplication.getInstance().getApplicationContext(), uri);
//            LogUtil.d("uploadtest", uri + "------" + realUri + "------" + qiNiuToken);
//            uploadManager.put(realUri, TimeUtil.getEasyNowDate(), qiNiuToken,
//                    new UpCompletionHandler() {
//                        @Override
//                        public void complete(String key, ResponseInfo info, JSONObject res) {
//                            //res包含hash、key等信息，具体字段取决于上传策略的设置
//                            if (info.isOK()) {
//                                Gson gson = new Gson();
//                                QiNiuInfo bean = gson.fromJson(res.toString(), QiNiuInfo.class);
//                                imgsList.add(Constants.QINIU_URL + bean.getKey());
//                            } else {
//                                LogUtil.i("qiniu", "Upload Fail");
//                                isUpLoadSuccess = false;
//                                //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
//                            }
//                            LogUtil.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
//                        }
//                    }, null);
//        }
//        if (!isUpLoadSuccess)
//            return null;
//        return imgsList;
//
//    }
//
//    private void doGoodsComment(GoodsComment goodsComment) {
//        addSubscribe(mDataManager.doGoodsCommentApi(goodsComment)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribeWith(new CommonSubscriber<HttpResponse>() {
//                    @Override
//                    public void onSuccess(HttpResponse httpResponse) {
//                        LogUtil.d(TAG, "success, doGoodsComment: " + httpResponse.getMessage());
//                        doCommentCalculate++;
//                        if (doCommentCalculate == mProductsList.size()) {
//                            mView.showFinishDoGoodsComment();
//                        }
//                    }
//
//                    @Override
//                    public void onFailed(String msg) {
//                        LogUtil.d(TAG, "fail, doGoodsComment: " + msg);
//                    }
//                }));
//    }
//
//    @Override
//    public void initList(final String orderNo) {
//        // TODO: 2018/4/30 0030 根据订单查询到所有的商品
//        addSubscribe(mDataManager.doGetOrderApi(Account.getInstance().getUserid(), null, orderNo)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .compose(RxUtil.<Orders>handleResult())
//                .subscribeWith(new CommonSubscriber<Orders>() {
//                    @Override
//                    public void onSuccess(Orders orders) {
//                        LogUtil.d(TAG, "success : doGetOrderApi: " + orderNo + ": --- " + orders.getOrders().getOrder().size());
//                        // TODO: 2018/5/8 0008 这里只是暂时去掉，因为现在的数据有重复的订单号
//                        /*if (orders.getOrders().getOrder().size() != 1) {
//                            LogUtil.d(TAG, "get order error");
//                            return;
//                        }*/
//
//                        Orders.OrdersBean.OrderBean order = orders.getOrders().getOrder().get(0);
//                        mProductsList = order.getProducts();
//                        List<AddComment> addCommentList = new ArrayList<>();
//                        for (Orders.OrdersBean.OrderBean.ProductsBean product : mProductsList) {
//                            AddComment addComment = new AddComment(product.getGoodsSkuImg(), Constants.HIGH, null, new ArrayList<Uri>(), false, product.getGoodsId(), product.getGoodsName());
//                            addCommentList.add(addComment);
//                        }
//
//                        mView.showInitList(addCommentList);
////                        //这里只是测试用,等XH改好用上面的订单编号获取订单方式
////                        for (Orders.OrdersBean.OrderBean orderBean : orders.getOrders().getOrder()) {
////                            if (Constants.ORDER_FINISHED == orderBean.getOrderStatus()) {
////                                LogUtil.d(TAG,"11111111");
////                                mView.showInitList(orderBean.getProducts());
////                                break;
////                            }
////                        }
//
//                    }
//
//                    @Override
//                    public void onFailed(String msg) {
//
//                    }
//                }));
//    }


}
